package com.mrobuy.jdvc.controller;

import com.mrobuy.jdvc.Result;
import com.mrobuy.jdvc.dao.TaskDao;
import com.mrobuy.jdvc.entity.Task;
import com.mrobuy.jdvc.entity.VCPurchaseSale;
import com.mrobuy.jdvc.entity.VCShelvesTask;
import com.mrobuy.jdvc.service.ShelvesService;
import com.mrobuy.jdvc.service.VCPurchaseSaleService;
import com.mrobuy.util.Pagination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 京东采销人员管理
 */
@Controller
public class PurchaseSaleController {

	private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");

	@Autowired
	private VCPurchaseSaleService vcPurchaseSaleService;


	@RequestMapping("shelves/purchasesale")
	public String task(Model model) {
		return "shelves/purchasesale";
	}


	/**
	 * 上架任务查询
	 */
	@RequestMapping("shelves/purchasesale/query")
	@ResponseBody
	public Object taskquery(HttpServletRequest request, VCPurchaseSale condition) {

		int start = ServletRequestUtils.getIntParameter(request, "start", 1);
		int length = ServletRequestUtils.getIntParameter(request, "length", 100);
		int draw = ServletRequestUtils.getIntParameter(request, "draw", 1);

		Pagination pagination = vcPurchaseSaleService.query(start, length, condition);

		pagination.setDraw(draw);

		return pagination;
	}

	/**
	 * 京东采销人员文件导入
	 */
	@RequestMapping("shelves/purchasesale/upload")
	@ResponseBody
	public Result upload(HttpServletRequest request, HttpServletResponse response, VCShelvesTask record) {

		String id = request.getParameter("id");
		List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
		if ( files!=null ) {
			for (MultipartFile file : files) {
				System.out.println(file.getOriginalFilename());

				try {
					vcPurchaseSaleService.importPurchaseSale(file.getInputStream());
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					try {
						file.getInputStream().close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}

		return new Result(true);
	}

}
